<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport( 'joomla.application.component.model' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JAJobBoardModelJACategories extends JModel
{
    var $_data;
    var $_table;
    
    /**
    * Get data list of configuration
    * @return array  Array of objects contain configuration data
    */
    function &getData(){
        // load data if it doesnnot already exists
        if(empty($this->_data)){
            $query = $this->_buildQuery(); 
            $this->_data = $this->_getList($query);
        }
        
        return $this->_data;
    }
    
    /**
    * Get configuration table instance
    * @return JTable Configuration table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_Categories', 'JobBoardTable');
		}		
		return $this->_table;
	}
		
	/**
	* Remove configuration record
	* @return Number of removed records
	*/
	function remove(){
	    $cid = JRequest::getVar('cid',array(), 'post', 'array');
	    $n =  count($cid);
	    JArrayHelper::toInteger( $cid );
	    
	    if($n){
	        $query = "DELETE FROM #__ja_categories WHERE id = ". implode(" OR id = ", $cid);
	        $db = &JFactory::getDBO();
	        $db->setQuery($query);
	        if($db->query()){
	            return $n;
			}
		}
		
		return -1;
	}
	
	/**
	* Get configuration item
	* @return Config Table object
	*/
	function getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}

		$table =& $this->_getTable();

		// Load the current item if it has been defined
		$edit	= JRequest::getVar('edit',true);
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		
		if ($edit) {
			$table->load($cid[0]);
		}

	    $item = $table;
	    return $item;	    
	}
	
	function _buildQuery($limitstart, $limit, $dosearch=false){
    	global $mainframe, $option;		
		$db = JFactory::getDBO();
    	
    	// Get the WHERE and ORDER BY clauses for the query
    	$search				= $mainframe->getUserStateFromRequest( "$option.jacategories.search", 'search', 	'',	'string' );
		$search				= JString::strtolower($search );
		$filter_state		= $mainframe->getUserStateFromRequest( "$option.jacategories.filter_state", 'filter_state', '',	'word' );
		
    	$where = '';
    	$where		= $this->_buildContentWhere($dosearch);
		$orderby	= $this->_buildContentOrderBy();		
		
		$feilds = ($dosearch)?'s.id':'*';
        $query = "SELECT $feilds "
        		 ."FROM #__ja_categories as s"
        		. $where
				. $orderby;
		if(!$search) $where .= "LIMIT $limitstart, $limit";
		
        return $query;
    }
    
    function _buildContentWhere($dosearch=false)
	{
		global $mainframe, $option;		
		$db = JFactory::getDBO();
		$option_1 = $option.'.jacategories';
		
		$search				= $mainframe->getUserStateFromRequest( "$option_1.search", 'search', 	'',	'string' );
		$search				= JString::strtolower($search );
		$filter_state		= $mainframe->getUserStateFromRequest( $option_1.'.filter_state', 'filter_state', '',	'word' );
		
		$where = ' WHERE 1=1 ';
		if($dosearch){
    		$where .= " AND LOWER(name) like ".$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
    	}

		if ( $filter_state )
		{
			if ( $filter_state == 'P' ) {
				$where .= ' AND s.published = 1';
			} else if ($filter_state == 'U' ) {
				$where .= ' AND s.published = 0';
			}
		}
		
		return $where;		
	}
    
	function _buildContentOrderBy()
	{
		global $mainframe, $option;
		
		$option_1 = $option.'.jacategories';
		$filter_order		= JRequest::getVar('filter_order', 's.name');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option_1.'.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		
		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , s.id ';
		
		return $orderby;
	}
	
	function getItems( $search=false ){
		global $mainframe, $option;
		
	    $limit		= $mainframe->getUserStateFromRequest( $option.'.jacategories.limitstart', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $option.'.jacategories.limitstart', 'limitstart', 0, 'int' );
		
		if(!$limit) $limit = $this->getTotal();
		$db = &JFactory::getDBO();
		
		$query = $this->_buildQuery($limitstart, $limit, $search);//echo $query;exit;
		$db->setQuery($query);
		$items = $db->loadObjectList();
		return $items;
	}

	function getSubcategories($catid, $ids=array()){
		if (!$catid) return array();
		if(!isset($db) || !$db) $db = JFactory::getDBO(); 
		$query = ' SELECT s.id '.
				 ' FROM #__ja_categories as s '.
				 " WHERE s.parent_id='$catid' and s.published=1";
		$db->setQuery($query);		
		$items = $db->loadObjectList();
		if($items){
			foreach ($items as $item){
				$ids[] = $item->id;
				$this->getSubcategories($item->id, $ids);
			}
		}
		return $ids;
	}
	
	function _buildQueryTotal()
	{
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();
		
		$query = ' SELECT count(*) '
			. ' FROM #__ja_categories as s '
			. $where
			. $orderby
		;
		
		return $query;
	}
	
	/**
	 * Method to get the total number of weblink items
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		$db = JFactory::getDBO();
		// Lets load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQueryTotal();
			$db->setQuery($query);
			$this->_total = $db->loadResult();
		}
		return $this->_total;
	}
	
	
	/** 
	* Store configuration item
	* @param array The post array
	*/
	function store(){
	    // Initialize variables
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem();
		$post	= $this->getState( 'request' );
		
		if (!$row->bind( $post )) {
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		 
		if (!$row->check())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
        
		if (!$row->store())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}
		
		$row->checkin();
		return $row->id;
	}	
	
	function storeData($catName, $parentID=0){	
		
		$db		=& JFactory::getDBO();
		$db->setQuery("INSERT INTO #__ja_categories(name, parent_id, published, ordering) VALUES('{$catName}', '{$parentID}', 1, 0)");
		$db->query();
		
		$db->setQuery("SELECT MAX(id) as id FROM #__ja_categories");
				
		return $db->loadResult();
	}
	
	/**
	 * Method to checkout/lock the jaconfig
	 *
	 * @access	public
	 * @param	int	$uid	User ID of the user checking the article out
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function checkout($uid = null)
	{
//		if ($this->_id)
//		{
//			// Make sure we have a user id to checkout the article with
//			if (is_null($uid)) {
//				$user	=& JFactory::getUser();
//				$uid	= $user->get('id');
//			}
//			// Lets get to it and checkout the thing...
//			$jaconfig = & $this->getTable();
//			if(!$jaconfig->checkout($uid, $this->_id)) {
//				$this->setError($this->_db->getErrorMsg());
//				return false;
//			}
//
//			return true;
//		}
		return true;
	}
	
	function dopublish($publish){
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());		
		$ids = implode( ',', $ids );
		
		$query = "UPDATE #__ja_categories"
		. "\n SET published = " . intval( $publish )
		. "\n WHERE id IN ( $ids )"
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}
}